import 'dart:convert';
import 'dart:math';

import 'package:aero_frisbee/app/model/af_home_user_model/af_home_user_model.dart';
import 'package:aero_frisbee/app/model/af_short_link_model/af_short_link_model.dart';
import 'package:aero_frisbee/app/model/cache_bind_video_model/cache_bind_video_model.dart';
import 'package:aero_frisbee/app/req/af_req_api.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'af_video_view_model.g.dart';

@Riverpod(keepAlive: true)
AfShortLinkModel curShortLink(CurShortLinkRef ref,
    {required AfShortLinkModel item}) {
  final curList = ref.watch(afVideoListServiceProvider).maybeWhen(
        orElse: () => List<AfShortLinkModel>.from([]),
        data: (data) => data,
      );
  return curList
      .where(
        (element) => element.mediaUrl == item.mediaUrl,
      )
      .last;
}

@Riverpod(keepAlive: true)
class AfVideoListService extends _$AfVideoListService {
  @override
  FutureOr<List<AfShortLinkModel>> build() async {
    final retlist = await ref.read(appApiProvider).shortLink();
    final vieoBindList = ref.read(videoBindCacheUserListServiceProvider);
    if (vieoBindList.isNotEmpty) {
      return Future.value(retlist
          .map(
            (e) => e.copyWith(
              cacheBind: vieoBindList.lastWhere(
                (element) => element.mediaPath == e.mediaPath,
              ),
            ),
          )
          .toList());
    } else {
      final userList = await ref.read(appApiProvider).fetchBroadcaster();
      List<CacheBindVideoModel> cacheBindList = [];
      var cpList = List<AfHomeUserModel>.from(userList);
      cpList.shuffle(Random());
      for (var i = 0; i < retlist.length; i++) {
        var element = cpList.length > i ? cpList[i] : null;
        cacheBindList.add(CacheBindVideoModel(
          mediaPath: retlist.isNotEmpty
              ? retlist[i].mediaPath
              : retlist.last.mediaPath,
          type: i % 3,
          homeUser: element,
        ));
      }
      ref
          .read(videoBindCacheUserListServiceProvider.notifier)
          .update(cacheBindList);

      return Future.value(retlist
          .map(
            (e) => e.copyWith(
                cacheBind: cacheBindList.lastWhere(
              (element) => element.mediaPath == e.mediaPath,
            )),
          )
          .toList());
    }
  }

  toggleLike({required AfShortLinkModel shortLinkeItem}) {
    final curPostList = state.maybeWhen(
      orElse: () => List<AfShortLinkModel>.from([]),
      data: (data) => data,
    );
    final retList = curPostList.map((e) {
      if (e == shortLinkeItem) {
        return e.copyWith(isLike: !e.isLike);
      } else {
        return e;
      }
    }).toList();
    state = AsyncData(retList);
  }
}

@Riverpod(keepAlive: true)
class VideoBindCacheUserListService extends _$VideoBindCacheUserListService {
  @override
  List<CacheBindVideoModel> build() {
    final userId = ref.watch(curlUserInfoProvider)?.userInfoModel?.userId;
    if (userId != null) {
      final prefs = ref.read(appPrefsProvider);
      final bindListStr = prefs.getString('bind.video.user.list.key_$userId');
      if (bindListStr != null && bindListStr.isNotEmpty) {
        final bindList = List<CacheBindVideoModel>.from(jsonDecode(bindListStr)
            .map((x) => CacheBindVideoModel.fromJson(x)));
        return bindList;
      }
    }
    return [];
  }

  update(List<CacheBindVideoModel> list) async {
    state = list;
    final userId = ref.read(curlUserInfoProvider)?.userInfoModel?.userId;
    if (userId != null) {
      final prefs = ref.read(appPrefsProvider);
      await prefs.setString(
          'bind.video.user.list.key_$userId', jsonEncode(list));
    }
  }
}
